package svc

import (
	"go-weixin/app/usercenter/api/internal/config"
	"go-weixin/app/usercenter/rpc/userrpcclient"
	"go-weixin/common/apiserver"
	"go-weixin/common/rpcserver"
	"strings"

	"github.com/zeromicro/go-queue/dq"
	"github.com/zeromicro/go-queue/kq"
	"github.com/zeromicro/go-zero/zrpc"
)

type ServiceContext struct {
	Config         config.Config
	UserRpc        userrpcclient.UserCenter
	KqClient       *kq.Pusher
	DqPusherClient dq.Producer
	ApiMDLE        *apiserver.Middleware
	RpcMDLE        *rpcserver.Middleware
}

func NewServiceContext(c config.Config) *ServiceContext {
	rpcMDLE := rpcserver.NewMiddleware()
	if c.UserRpc.HostList != "" {
		c.UserRpc.Endpoints = strings.Split(c.UserRpc.HostList, ";")
	}
	userRpc := userrpcclient.NewUserRpcClient(zrpc.MustNewClient(zrpc.RpcClientConf{Endpoints: c.UserRpc.Endpoints, NonBlock: c.UserRpc.NonBlock}, zrpc.WithUnaryClientInterceptor(rpcMDLE.ClientRpcMiddleware)))

	// 延时任务config
	var dqBeanstalk []dq.Beanstalk
	if len(c.Dqconf.Beanstalks) > 0 {
		for _, bk := range c.Dqconf.Beanstalks {
			dqBeanstalk = append(dqBeanstalk, dq.Beanstalk{
				Endpoint: bk.Endpoint,
				Tube:     bk.Tube,
			})
		}
	}

	return &ServiceContext{
		Config:         c,
		UserRpc:        userRpc,
		ApiMDLE:        apiserver.NewApiMiddleware(userRpc),
		RpcMDLE:        rpcMDLE,
		KqClient:       kq.NewPusher(c.KqPusherConf.Brokers, c.KqPusherConf.Topic),
		DqPusherClient: dq.NewProducer(dqBeanstalk)}
}
